package handler

import (
	"context"
	"encoding/json"
	"goods_srv/global"
	"goods_srv/goodsPb"
	"goods_srv/model"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

// 获取全部分类
func (g *GoodsService) GetAllCategoryList(ctx context.Context, in *goods_pb.Empty) (*goods_pb.CategoryListResponse, error) {

	var cateGory []model.Category

	res := global.DB.Model(model.Category{}).Where(model.Category{Level: 1}).Preload("SubCategory.SubCategory").Find(&cateGory)
	if res.Error != nil {
		return nil, res.Error
	}
	marshal, _ := json.Marshal(cateGory)

	return &goods_pb.CategoryListResponse{
		JsonData: string(marshal),
	}, nil
}

// 添加分类
func (g *GoodsService) CreateCategory(ctx context.Context, in *goods_pb.CategoryInfoRequest) (*goods_pb.CategoryInfoResponse, error) {
	cateGory := model.Category{}
	cateGory.Name = in.Name
	cateGory.Level = in.Level
	if in.Level != 1 {
		cateGory.ParentCategoryID = in.ParentCategory
	}
	cateGory.IsTab = in.IsTab

	res := global.DB.Create(&cateGory)
	if res.Error != nil {
		return nil, status.Errorf(codes.Internal, "新增分类失败")
	}
	return &goods_pb.CategoryInfoResponse{
		Id:             cateGory.ID,
		Name:           cateGory.Name,
		ParentCategory: cateGory.ParentCategoryID,
		Level:          cateGory.Level,
		IsTab:          cateGory.IsTab,
	}, nil
}

// 删除分类
func (g *GoodsService) DeleteCategory(ctx context.Context, in *goods_pb.DeleteCategoryRequest) (*goods_pb.Empty, error) {
	res := global.DB.Where("id = ?", in.Id).Delete(&model.Category{})
	if res.RowsAffected == 0 {
		return nil, status.Errorf(codes.Internal, "分类不存在")
	}
	return &goods_pb.Empty{}, nil
}

// 更新分类
func (c *GoodsService) UpdateCategory(ctx context.Context, in *goods_pb.CategoryInfoRequest) (*goods_pb.Empty, error) {
	res := global.DB.Where("id = ?", in.Id).Updates(&model.Category{
		Name:             in.Name,
		ParentCategoryID: in.ParentCategory,
		Level:            in.Level,
		IsTab:            in.IsTab,
	})
	if res.RowsAffected == 0 {
		return nil, status.Errorf(codes.Internal, "分类不存在")
	}
	return &goods_pb.Empty{}, nil
}
